import React, { useState, useEffect } from 'react'; 
import { Table, Button, Modal } from 'antd';
import {request} from "../utils/requset";

function FileListTable() {
    const [fileList, setFileList] = useState([]);
    const [fileDataList, setFileDataList] = useState([]);
    const [visible, setVisible] = useState(false);

    useEffect(() => {
        fetchFileList();
    }, []);

    const fetchFileList = async () => {
        try {
            const response = await request.get('/rpa/pdfDownload/runList');
            setFileList(response.data.data);
        } catch (error) {
            console.error('Error fetching file list:', error);
        }
    };

    const fetchFileData = async (id) => {
        try {
            const response = await request.get('/rpa/pdfDownload/dataList?id=' + id);
            setFileDataList(response.data.data);
        } catch (error) {
            console.error('Error fetching file data:', error);
        }
    };

    const showModal = (record) => {
        fetchFileData(record.id);
        setVisible(true); // 打开模态框
    };

    const handleCancel = () => {
        setVisible(false); // 关闭模态框
        setFileDataList([]); // 清空 fileDataList
    };

    const fileDownload = async (record) => {
        try {
          const response = await request.get('/rpa/pdfDownload/fileDownload?id=' + record.id, {
            responseType: 'blob' // 告诉 request 返回的是二进制文件
          });
      
          // 创建一个URL对象，指向Blob
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', record.realName); // 这里的name是文件名
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } catch (error) {
          console.error('Error downloading file:', error);
        }
      };

    const columns = [
        {
            title: '名称',
            dataIndex: 'realName',
            key: 'realName',
            render: (text, record) => (
                record.type !== 'file' ? 
                <span>
                    {record.realName} 
                </span> : 
                <span>
                    <Button type="link" style={{padding: 0}} onClick={() => fileDownload(record)}>{record.realName}</Button>
                </span>
            ),
        },
        {
            title: '日期',
            dataIndex: 'importDate',
            key: 'importDate',
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <span>
                    <Button type="link" disabled={record.status === '未执行'} onClick={() => showModal(record)}>查看</Button>
                    <Button type="link" disabled={record.status === '未执行'} onClick={() => request.post('/rpa/openFolder?path=' + record.path)}>打开文件夹</Button>
                </span>
            ),
        },
    ];

    const entryColumns = [
        {
            title: '文件名',
            dataIndex: 'fileName',
            key: 'fileName',
        },
        {
            title: '年',
            dataIndex: 'year',
            key: 'year',
        },
        {
            title: '月',
            dataIndex: 'month',
            key: 'month',
        },
        {
            title: '凭证号',
            dataIndex: 'pzh',
            key: 'pzh',
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                record.id.split(";").length === 1 ?
                <span>
                    <Button type="link" onClick={() => {request.get('/rpa/pdf/download?id='+record.id)}}>预览</Button>
                </span> :
                <span>
                    <Button type="link" onClick={() => {request.get('/rpa/pdf/download?id='+record.id.split(";")[0])}}>预览</Button>
                    <Button type="link" onClick={() => {request.get('/rpa/pdf/download?id='+record.id.split(";")[1])}}>原PDF</Button>
                </span>
            ),
        },
    ];

    return (
        <div style={{ height: 'calc(100vh - 368.47px)' }}> 
            <Table 
                dataSource={fileList} 
                columns={columns} 
                rowKey="id" 
                scroll={{ y: `max(200px, calc(100vh - 487.14px))` }}
            />
            
            <Modal
                title="文件数据"
                open={visible}
                onCancel={handleCancel}
                footer={null}
                width={"70vw"}
            >
                <Table
                    dataSource={fileDataList}
                    columns={entryColumns}
                    rowKey="id"
                    scroll={{ y: 600 }}
                    // pagination={false} // 如果不需要分页，可以禁用分页
                />
            </Modal>
        </div>
    );
};

export default FileListTable;
